import optparse
import socket
#
# server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# server.bind(('localhost',8888))
#
# server.listen(5)
#
# client,addr = server.accept()
# print('客户端链接成功',addr)
# data = client.recv(1024)
# print('收到数据',data.decode())
# msg = input('请输入你要和客户端回复的消息：')
# client.send(msg.encode())
#
# client.close()
# server.close()
#
# client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#
# client.connect(('127.0.0.1',8888))
#
# client.send('hello'.encode())
#
# data = client.recv(1025)
# print('客户端收到数据：',data.decode())
# client.close()
#
# import socket
# def scan_port(ip,port):
#     try:
#         sock = socket.socket(socket.AF_INET)
#
# client = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
# client.connect(('127.0.0.1',8888))
# client.send('hello'.encode())
# data = client.recv(1024)
# print("客户端收到数据：",data.decode())
# client.close()
# import socket


def main():
    # 创建一个socket对象
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到服务器
    server_address = ('localhost', 8888)
    print(f'连接到 {server_address[0]}:{server_address[1]}')
    client_socket.connect(server_address)

    try:
        # 发送数据到服务器
        message = '你好，服务器！'
        print(f'发送数据: {message}')
        client_socket.sendall(message.encode())

        # 接收来自服务器的数据
        amount_received = 0
        data = b''
        while amount_received < 1024:  # 假设我们最多接收1024字节
            data += client_socket.recv(1024 - amount_received)
            amount_received = len(data)

        print(f'收到数据: {data.decode()}')

    finally:
        # 关闭连接
        print('关闭连接')
        client_socket.close()


if __name__ == '__main__':
    main()


def port_scan(ip, port):
    try:
        s = socket.socket()
        s.settimeout(5)
        if s.connect_ex((ip, port)) == 0:
            print(f'[+] Host {ip}, Port {port}, Status: OPEN')
        else:
            print(f'[+] Host {ip}, Port {port}, Status: CLOSED')
    except Exception as e:
        print(e)
    finally:
        s.close() if 's' in locals() and s else None  # 确保在异常情况下也能关闭socket


def main():
    parser = optparse.OptionParser('Usage: %prog -i <target ip> -p <target port> (or range, e.g., 8000-9000)')
    parser.add_option('-i', dest='ip', type='string', help='target ip')
    parser.add_option('-p', '--port', dest='port', type='string',
                      help='target port, can be a single port or a range, e.g., 8000-9000')
    opts, args = parser.parse_args()

    ip = opts.ip
    port = opts.port

    if not ip or not port:
        parser.print_help()
        return

    try:
        if '-' in port:
            start_port, end_port = map(int, port.split('-'))
            for p in range(start_port, end_port + 1):
                port_scan(ip, p)
        else:
            port_scan(ip, int(port))
    except ValueError:
        print("Invalid port number or range.")
        parser.print_help()


if __name__ == '__main__':
    main()

